<template>
  <view class="st-u-comment">
    <view class="comment" v-for="(item, index) in commentSubjectDataList" :key="item.id">
<!--      左侧-->
      <view class="left">
        <!--头像信息-->
        <u-avatar :src="item.ownerUserAvatar" @tap="$emit('avatarClick',item)" mode="circle" :size="64"
                  :show-sex="!!genderResolve(item)" :sex-icon="gender[genderResolve(item)]" ></u-avatar>
      </view>
      <!--      右侧-->
      <view class="right">
        <!--        右侧顶部-->
        <view class="top">
          <view class="name-box">
            <!--            昵称-->
            <view class="nickname">{{ item.ownerUserNickname }}</view>
            <!--            自定义槽-->
            <slot name="rightSubTitle" v-bind:commentSubject="item"></slot>
            <!-- 自定义昵称下方文字 和 slot name=rightSubTitle 一般二选一即可-->
            <template>
              <view style="font-size: 25rpx; color: grey;" >
                <template v-for="(item,index) in rightSubTitleData(item)">
                  <text class='iconfont' v-if="item.icon" :class="item.icon"></text>
                  <text v-if="item.text" style="margin-right: 20rpx;">{{ item.text }}</text>
                </template>
              </view>
            </template>
          </view>
          <!-- 右侧点赞-->
          <view class="like" :class="{ highlight: item.isMeHasStared }">
            <view class="num">{{ item.starCount }}</view>
            <u-icon v-if="!item.isMeHasStared" name="thumb-up" :size="30" color="#9a9a9a" @click="starOrCancel(item)"></u-icon>
            <u-icon v-if="item.isMeHasStared" name="thumb-up-fill" :size="30" @click="starOrCancel(item)"></u-icon>
          </view>
        </view>
        <!-- 评论内容-->
        <view class="content">{{ item.content }}</view>

        <!--点赞列表-->
        <view v-if="item.latestCommentSubjectStars && item.latestCommentSubjectStars.records.length > 0" class="st-flex star-box"
              style="margin-top: 20rpx;padding: 20rpx; background-color: #f3f3f5;" :class="{'star-box-border-bottom':item.latestCommentSubjects && item.latestCommentSubjects.records.length > 0}">
          <!-- 点赞人的头像-->
          <template v-for="(starItem,index) in item.latestCommentSubjectStars.records">
            <u-image @tap="starAvatarClick(item,starItem)"  :src="starItem.ownerUserAvatar" :width="35" :height="35" shape="circle" mode="aspectFill" :key="index">
            </u-image>
          </template>
          <view class="all-star" @tap="toAllStar(item)" v-if="item.starCount > 0">
            {{ item.starCount }}人赞过
            <u-icon class="more" name="arrow-right" :size="20"></u-icon>
          </view>
        </view>
        
        <!-- 回复区域-->
        <view class="reply-box" v-if="item.latestCommentHierarchicals && item.latestCommentHierarchicals.records.length > 0">
          <view class="item" v-for="(hierarchicalItem, hierarchicalIndex) in item.latestCommentHierarchicals.records" :key="hierarchicalIndex">
            <view class="st-flex">
              <u-image @tap="commentHierarchicalAvatarClick(item,hierarchicalItem)" :src="hierarchicalItem.ownerUserAvatar" :width="35" :height="35" shape="circle" mode="aspectFill" style="margin-bottom: -3rpx;">
              </u-image>
              <text class="username">{{ hierarchicalItem.ownerUserNickname }}</text>
            </view>
            <!-- 回复内容-->
            <view class="text">
              <text class="content">{{ hierarchicalItem.content }}</text>
              <text class="reply" @tap="commentReplyClick(item,hierarchicalItem)">{{ hierarchicalItem.commentCount>0 ? hierarchicalItem.commentCount : ''}}回复<u-icon class="more" name="arrow-right" :size="20"></u-icon></text>
            </view>
          </view>
          <view class="all-reply" @tap="toAllReply(item)" v-if="item.commentCount > 0">
            共{{  item.commentCount }}条回复
            <u-icon class="more" name="arrow-right" :size="26"></u-icon>
          </view>
        </view>
        <!-- 底部回复-->
        <view class="bottom">
          {{ item.timeAt }}
          <view class="reply" @click="replyClick(item)">回复</view>
        </view>
      </view>
    </view>
    <!--加载更多-->
    <stULoadmore ref="loadMore" :ready="loadCommentData" @loadmore="loadCommentData"></stULoadmore>

  </view>
</template>

<script>
import stULoadmore from '../../../../../../common/web/components/app/uni-app/uview/st-u-loadmore/st-u-loadmore.vue'
import CommentSubjectUrl from '../../../../pc/subject/CommentSubjectUrl.js'
import CommentSubjectStarUrl from '../../../../pc/subject/CommentSubjectStarUrl.js'
export default {
  components: {stULoadmore},
  props: {
    /**
     * 主体id
     */
    subjectId: {
      type: String,
      required: true
    },
    // 分组标识
    groupFlag: {
      type: String,
    },
    // 获取性别
    genderResolve: {
      type: Function,
      default: (commentSubject)=>{
        let r = ''
        if(commentSubject.ext){
          return commentSubject.ext.genderDictValue
        }
        return r
      }
    },
    // 右侧昵称下方文本数据,与slot=rightSubTitle 二选一即可
    // 返回数组元素应包含 {icon:'',text: ''}
    rightSubTitleData:{
      type: Function,
      default: (commentSubject)=>{
        return []
      }
    },
    // 当前登录的用户id，如果不传默认使用 vuex_userInfo.id
    userId: {
      type: String
    }
  },
  data() {
    return {
      // 评论列表
      commentSubjectDataList: [],
      // 查询参数
      commentQuery: {
        current: 1,
        subjectId: this.subjectId,
        groupFlag: this.groupFlag
      }
    };
  },
  mounted() {
  },
  methods: {
    // 跳转到全部回复
    toAllReply(commentSubject) {
      this.$emit('toAllReply',commentSubject)

    },
    replyClick(commentSubject){
      this.$emit('replyClick',commentSubject)
    },
    commentHierarchicalAvatarClick(commentSubject,hierarchicalItem){
      this.$emit('commentHierarchicalAvatarClick', {commentSubject,hierarchicalItem})
    },
    // 加载数据
    loadCommentData(refresh,callback=()=>{}) {
      if(!refresh && this.$refs.loadMore && !this.$refs.loadMore.canLoad()){
        if(callback){
          callback()
        }
        return
      }
      this.$http.get(CommentSubjectUrl.getAvailablePage,{params:this.commentQuery}).then(res => {
        if (this.commentQuery.current == 1) {
          this.commentSubjectDataList = []
        }
        res.data.records.forEach(item =>{
          this.commentSubjectDataList.push(item)
        });
        this.commentQuery.current = res.data.current + 1
        this.$refs.loadMore.loaded(res.data)
      }).catch((error)=>{
        this.$u.toast('抱歉系统出错误了')
        console.error(error)
        this.$refs.loadMore.loadError()
      }).finally(()=>{
        if(callback){
          callback()
        }
      })
    },
    // 刷新数据
    refreshCommentData(callback=()=>{}){
      this.commentQuery.current = 1
      this.loadCommentData(true,callback)
    },
    // 在数据前添加一条，主要用于 comment 发布成功后不用去后台请求数据，直接添加一条即可
    prepend(comment){
      if (!comment) {
        return
      }
      this.commentSubjectDataList.unshift(comment)
    },
    // 在数据前添加一条评论，主要用于 comment 发布成功后不用去后台请求数据，直接添加一条即可
    prependCommentHierarchical(commentHierarchical){
      let commentSubjectData = this.getByCommentSubjectId(commentHierarchical.subjectId)
      if (!commentSubjectData) {
        console.error('prependComment 没有找到数据，可能访问出现了问题，重新进入页面可能会正常，subjectId=' + commentSubjectData.subjectId)
        return
      }
      if(!commentSubjectData.latestCommentHierarchicals){
        this.$set(commentSubjectData,'latestCommentHierarchicals',{records: []})
      }
      commentSubjectData.commentCount += 1
      commentSubjectData.latestCommentHierarchicals.records.unshift(commentHierarchical)
    },
    getByCommentSubjectId(commentSubjectId){
      let filtered = this.commentSubjectDataList.filter(item => commentSubjectId == item.id)
      if(filtered.length > 0){
        return filtered[0]
      }
      return null;
    },
    // 点击点赞区头像事件
    starAvatarClick(commentSubject,starItem){
      this.$emit('starAvatarClick', {commentSubject,starItem})
    },
    // 点击全部点赞事件
    toAllStar(commentSubject){
      this.$emit('toAllStarClick',commentSubject)
    },
    // 点赞或取消
    starOrCancel(commentSubject){
      if (commentSubject.isMeHasStared) {
        // 最后面的参数 true 表示立即执行
        this.$u.debounce(()=>{this.doCancelStar(commentSubject)}, 800,true)
      }else {
        this.$u.debounce(()=>{this.doStar(commentSubject)}, 800,true)
      }
    },
    // 点赞发起请求
    doStar(commentSubject){
      this.checkLogin().then(()=>{
        let data = {
          commentSubjectId: commentSubject.id,
          groupFlag: this.groupFlag
        }
        this.$http.post(CommentSubjectStarUrl.addStar,data).then((res)=>{
          commentSubject.isMeHasStared = true
          commentSubject.starCount += 1
          this.prependStar(commentSubject,res.data)
        })
      })
    },
    // 取消点赞发起请求
    doCancelStar(commentSubject){
      this.checkLogin().then(()=>{
        let data = {
          commentSubjectId: commentSubject.id,
          groupFlag: this.groupFlag
        }
        this.$http.post(CommentSubjectStarUrl.cancelStar,data).then(()=>{
          commentSubject.isMeHasStared = false
          commentSubject.starCount -= 1
          this.removeStar(commentSubject)
        })
      })
    },
    // 在数据前添加一条点赞，主要用于 commentSubjectStar 发布成功后不用去后台请求数据，直接添加一条即可
    prependStar(commentSubject,commentSubjectStar){
      if(!commentSubject.latestCommentSubjectStars){
        this.$set(commentSubject,'latestCommentSubjectStars',{records: []})
      }
      commentSubject.latestCommentSubjectStars.records.unshift(commentSubjectStar)
    },
    // 取消点赞使用，移除当前用户已点赞的数据
    removeStar(commentSubject){
      if(commentSubject.latestCommentSubjectStars){
        let userId = this.userId || this.vuex_userInfo.id
        let a = commentSubject.latestCommentSubjectStars.records
        for (let i = 0; i < a.length; i++) {
          if(a[i].ownerUserId == userId){
            a.splice(i,1)
            return
          }
        }
      }
    },
    // 单条评论回复点击事件
    commentReplyClick(commentSubject,hierarchicalItem){
      this.$emit('commentReplyClick', {commentSubject,hierarchicalItem})
    },
  }
};
</script>

<style lang="scss" scoped>
.comment {
  display: flex;
  padding: 30rpx;

  .right {
    flex: 1;
    padding-left: 20rpx;
    font-size: 30rpx;
    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10rpx;
      .name-box {
        .nickname{
          color: #5677fc;
        }
      }
      .like {
        display: flex;
        align-items: center;
        color: #9a9a9a;
        font-size: 26rpx;
        .num {
          margin-right: 4rpx;
          color: #9a9a9a;
        }
      }
      .highlight {
        color: #5677fc;
        .num {
          color: #5677fc;
        }
      }
    }
    .content {
      margin-bottom: 10rpx;
    }
    .reply-box {
      background-color: rgb(242, 242, 242);
      border-radius: 12rpx;
      .item {
        padding: 20rpx;
        border-bottom: solid 2rpx $u-border-color;
        .username {
          font-size: 24rpx;
          color: #999999;
        }
        .text{
          margin-top: 10rpx;
          font-size: 26rpx;

          .reply{
            margin-left: 10rpx;
            color: #5677fc;
            font-size: 26rpx;
            .more {
              margin-left: 3rpx;
            }
          }
        }
      }
      .all-reply {
        padding: 20rpx;
        display: flex;
        color: #5677fc;
        align-items: center;
        .more {
          margin-left: 6rpx;
        }
      }
    }
    .star-box{
      border-radius: 12rpx;
      margin-bottom: 12rpx;
      .star-box-border-bottom{
        border-bottom: solid 2rpx $u-border-color;

      }
      .all-star {
        padding-left: 20rpx;
        display: flex;
        color: #5677fc;
        align-items: center;
        .more {
          margin-left: 3rpx;
        }
      }
    }
    .bottom {
      margin-top: 20rpx;
      display: flex;
      font-size: 24rpx;
      color: #9a9a9a;
      .reply {
        color: #5677fc;
        margin-left: 10rpx;
      }
    }
  }
}
</style>
